<template>
  <div class="accessory-select">
    <el-checkbox-group v-model="selectedValues" @change="handleChange">
      <div v-for="item in options" :key="item.id || item.value" class="accessory-item">
        <el-checkbox
          :value="item.value"
          :disabled="disabled"
          @change="handleBoxChange(item, $event)"
        >
          {{ item.label }}
        </el-checkbox>

        <!-- 选中时显示输入框 -->
        <div v-if="isAccessorySelected(item.value)" class="accessory-input-group">
          <el-input-number
            :model-value="getAccessoryValue(item.value)"
            class="accessory-input"
            placeholder="数量"
            :min="0"
            :precision="2"
            size="small"
            @change="handleAccessoryValueChange(item.value, $event)"
          />
          <!-- 显示宽度和高度（转换为米） -->
          <span class="size-display">
            宽: {{ (width / 1000).toFixed(2) }}m 高: {{ (height / 1000).toFixed(2) }}m
          </span>

          <!-- 快速填入按钮 -->
          <div class="quick-fill-buttons">
            <el-button
              size="small"
              type="primary"
              plain
              @click="handleQuickFill(item.value, width)"
            >
              按宽度
            </el-button>
            <el-button
              size="small"
              type="primary"
              plain
              @click="handleQuickFill(item.value, height)"
            >
              按高度
            </el-button>
          </div>
        </div>
      </div>
    </el-checkbox-group>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useVtOptionsStore } from "@/store/modules/vt-options.store.js";

defineOptions({
  name: "AccessorySelect",
  inheritAttrs: false,
});

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  width: {
    type: Number,
    default: 0,
  },
  height: {
    type: Number,
    default: 0,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:modelValue", "change"]);

const vtOptionsStore = useVtOptionsStore();
const loading = ref(false);
const options = ref([]);

// 选中的值
const selectedValues = computed({
  get() {
    // 从 "配件名-数量" 格式中提取配件名
    return (props.modelValue || []).map((value) => {
      const parts = value.split("-");
      return parts[0]; // 返回配件名部分
    });
  },
  set(value) {
    // 保持用户自定义的数量值
    const newValues = value.map((accessoryName) => {
      const existingValue = (props.modelValue || []).find((v) => v.startsWith(accessoryName + "-"));
      return existingValue || `${accessoryName}-0`; // 如果没有数量，默认为0
    });
    emit("update:modelValue", newValues);
  },
});

// 加载配件选项数据
async function loadOptions() {
  loading.value = true;
  try {
    options.value = await vtOptionsStore.getAccessoryOptions();
  } catch (error) {
    console.error("AccessorySelect: 加载配件选项失败", error);
    options.value = [];
  } finally {
    loading.value = false;
  }
}

function handleChange(values) {
  // 保持用户自定义的数量值
  const newValues = values.map((accessoryName) => {
    const existingValue = (props.modelValue || []).find((v) => v.startsWith(accessoryName + "-"));
    return existingValue || `${accessoryName}-0`;
  });
  const selectedOptions = options.value.filter((item) => values.includes(item.value));
  emit("change", newValues, selectedOptions);
}

//默认选中时，按宽度填充
function handleBoxChange(item, event) {
  if (event) {
    handleQuickFill(item.value, props.width);
  }
}

function handleAccessoryValueChange(accessoryName, quantity) {
  const currentValues = props.modelValue || [];
  const newValues = currentValues.map((value) => {
    if (value.startsWith(accessoryName + "-")) {
      return `${accessoryName}-${quantity}`;
    }
    return value;
  });

  // 如果配件不在当前值中，添加它
  if (!currentValues.some((v) => v.startsWith(accessoryName + "-"))) {
    newValues.push(`${accessoryName}-${quantity}`);
  }

  emit("update:modelValue", newValues);
}

function handleQuickFill(accessoryName, sizeValue) {
  // 将毫米转换为米，保留2位小数
  const meterValue = (sizeValue / 1000).toFixed(2);
  handleAccessoryValueChange(accessoryName, parseFloat(meterValue));
}

// 检查配件是否被选中
function isAccessorySelected(accessoryName) {
  return (props.modelValue || []).some((value) => value.startsWith(accessoryName + "-"));
}

// 获取配件的数量值
function getAccessoryValue(accessoryName) {
  const accessoryValue = (props.modelValue || []).find((value) =>
    value.startsWith(accessoryName + "-")
  );
  if (accessoryValue) {
    const parts = accessoryValue.split("-");
    return parseFloat(parts[1]) || 0;
  }
  return 0;
}

onMounted(() => {
  loadOptions();
});
</script>

<style scoped lang="scss">
.accessory-select {
  width: 100%;

  .accessory-item {
    display: flex;
    flex-direction: column;
    margin-bottom: 12px;

    .el-checkbox {
      margin-bottom: 8px;
    }

    .accessory-input-group {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 8px;
      margin-left: 24px;

      .accessory-input {
        width: 120px;
      }

      .size-display {
        font-size: 12px;
        color: #666;
        white-space: nowrap;
      }

      .quick-fill-buttons {
        display: flex;
        gap: 4px;

        .el-button {
          font-size: 12px;
          padding: 2px 6px;
          height: auto;
        }
      }
    }
  }

  :deep(.el-checkbox-group) {
    display: flex;
    flex-direction: column;
  }

  :deep(.el-checkbox) {
    margin-right: 0;
    margin-bottom: 0;
  }
}
</style>
